package com.app.dao.impl;

import com.app.common.AppException;
import com.app.dao.IUserDao;
import com.app.pojo.User;
import com.app.utils.JDBCTemplate;
import com.app.utils.WhereCause;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C) @2020 fgwang.660@gmail.com
 *
 * @author witt
 * @version 1.0
 * @className UserDao
 * @date 2020-06-14 17:31
 * @description User  持久层实现类
 */
public class UserDao implements IUserDao {
	/*
	 * 注入JDBC 模板对象
	 */
	private final JDBCTemplate jdbcTemplate = new JDBCTemplate();

	/**
	 * select * from XXXX 抽象方法
	 *
	 * @return 对象数据集合
	 */
	@Override
	public List<User> select() {
		try {
			return jdbcTemplate.select(User.class);
		} catch (SQLException e) {
			throw new AppException(e);
		}
	}

	/**
	 * 查询单条数据
	 *
	 * @param id
	 * @return
	 */
	@Override
	public User select(Integer id) {
		List<WhereCause> params = new ArrayList<>();
		params.add(new WhereCause()
				.setKey("id")
				.setCondition(WhereCause.EQUAL)
				.setValue(id));
		try {
			return jdbcTemplate.selectBean(User.class, params);
		} catch (SQLException e) {
			throw new AppException(e);
		}
	}

	/**
	 * 通过loginId查询
	 *
	 * @param loginId
	 * @return
	 */
	@Override
	public User select(String loginId) {
		// 参数列表
		List<WhereCause> param = new ArrayList<>();

		param.add(new WhereCause()
				.setKey("login_id")
				.setValue(loginId)
				.setCondition(WhereCause.EQUAL)
				.setNumber(false));
		try {
			return jdbcTemplate.selectBean(User.class, param);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new AppException(e);
		}
	}

	/**
	 * 新增单条记录
	 *
	 * @param user 数据对象
	 * @return 主键id
	 */
	@Override
	public Integer insert(User user) {
		try {
			user.setDisable(false)
				.setCreatedTime(LocalDateTime.now())
				.setUpdateTime(LocalDateTime.now());
			return jdbcTemplate.insert(user);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new AppException(e);
		}
	}

	/**
	 * 更新单条数据
	 *
	 * @param user
	 */
	@Override
	public void update(User user) {
		try {
			user.setUpdateTime(LocalDateTime.now());
			jdbcTemplate.update(user);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new AppException(e);
		}
	}

	/**
	 * 删除记录
	 *
	 * @param ids 支持一次删多条
	 */
	@Override
	public void delete(String ids) {
		List<WhereCause> params = new ArrayList<>();
		params.add(new WhereCause()
				.setKey("id")
				.setCondition(WhereCause.IN)
				.setValue(ids)
				.setNumber(true));
		try {
			jdbcTemplate.delete(User.class, params);
		} catch (SQLException e) {
			throw new AppException(e);
		}
	}

}
